<template>
  <div class="xtx-pagination">
    <a href="javascript:;" :class="{disabled:currentPage<=1}" @click="changePage(currentPage-1)">上一页</a>
    <span v-if="pageArr[0] > 1">...</span>
    <a href="javascript:;" :class="{active:i===currentPage}" v-for="i in pageArr" :key="i" @click="changePage(i)">{{
        i
      }}</a>
    <span v-if="pageArr[pageArr.length-1] <totalPage">...</span>
    <a href="javascript:;" @click="changePage(currentPage+1)" :class="{disabled:currentPage>=totalPage}">下一页</a>
  </div>
</template>
<script>
import { computed } from 'vue'

export default {
  name: 'XtxPagination',
  props: {
    currentPage: {
      //  当前页
      type: Number,
      default: 1
    },
    totalPage: {
      //  总页码
      type: Number,
      default: 100
    },
    pageSize: {
      type: Number,
      default: 10
    }
  },
  setup (props, { emit }) {
    //  上下页点击事件
    function changePage (val) {
      // let page = props.currentPage + val
      // console.log(page)
      if (val < 1 || val > props.totalPage) return
      // console.log(111)
      emit('changePage', val)
    }

    //页码容量
    const pageArrLength = 5
    //  页码列表
    const pageArr = computed(() => {
      let minPage = props.currentPage - Math.floor(pageArrLength / 2) < 1 ? 1 : props.currentPage - Math.floor(pageArrLength / 2)
      if (minPage > props.totalPage - pageArrLength + 1) minPage = props.totalPage - pageArrLength + 1
      // console.log(minPage)
      const maxPage = minPage + pageArrLength
      const arr = []
      for (let i = minPage; i < maxPage; i++) {
        arr.push(i)
      }
      // console.log(arr)
      return arr
    })
    return {
      changePage,
      pageArr
    }
  }

}
</script>
<style scoped lang="less">
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;

  > a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;

    &:hover {
      color: @xtxColor;
    }

    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }

    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;

      &:hover {
        color: #333
      }
    }
  }

  > span {
    margin-right: 10px;
  }
}
</style>
